package com.ry.framework.shiro.session;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.SerializationUtils;

import com.ry.common.utils.JedisUtils;

public class RedisSessionDao extends AbstractSessionDAO {
	
	private final String shiro_session_prefix = "shiro-session:";
	
	@Autowired
	private JedisUtils jedisUtils;
	
	private byte[] getKey(String key) {
		return (shiro_session_prefix + key).getBytes();
	}
	
	private void saveSession(Session session) {
		if(session != null && session.getId() != null ) {
			byte []key = getKey(session.getId().toString());
			byte []value = SerializationUtils.serialize(session);
			jedisUtils.set(key, value);
			jedisUtils.expire(key, 600);
		}
	}
	
	@Override
	protected Serializable doCreate(Session session) {
		// TODO Auto-generated method stub
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		saveSession(session);
		
		return sessionId;
	}
	
	@Override
	protected Session doReadSession(Serializable sessionId) {
		System.out.println("read session");
		// TODO Auto-generated method stub
		if(sessionId == null) {
			return null;
		}
		byte []key = getKey(sessionId.toString());
		byte []value = jedisUtils.get(key);
		return (Session)SerializationUtils.deserialize(value);
	}
	
	@Override
	public void update(Session session) throws UnknownSessionException {
		// TODO Auto-generated method stub
		saveSession(session);
	}
	
	@Override
	public void delete(Session session) {
		// TODO Auto-generated method stub
		if(session != null && session.getId() != null ) {
			return;
		}
		byte []key = getKey(session.getId().toString());
		jedisUtils.del(key);
	}

	@Override
	public Collection<Session> getActiveSessions() {
		// TODO Auto-generated method stub
		Set<byte[]> keys = jedisUtils.keys(shiro_session_prefix);
		
		Set<Session> sessions = new HashSet<Session>();
		if(CollectionUtils.isEmpty(keys)) {
			return sessions;
		}
		for (byte[] key : keys) {
			Session session = (Session) SerializationUtils.deserialize(jedisUtils.get(key));
			sessions.add(session);
		}
		
		return null;
	}

	@Override
	protected void assignSessionId(Session session, Serializable sessionId) {
		// TODO Auto-generated method stub
		super.assignSessionId(session, sessionId);
	}
	
}
